<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="SKU编码" prop="sku">
        <el-input
          v-model="queryParams.sku"
          placeholder="请输入SKU编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属店铺" prop="shopId">
        <el-select v-model="queryParams.shopId" placeholder="请选择店铺" clearable>
          <el-option
            v-for="item in shopOptions"
            :key="item.shopId"
            :label="item.shopName"
            :value="item.shopId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退货日期">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['stock:return:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['stock:return:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['stock:return:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['stock:return:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="returnList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="SKU编码" align="center" prop="sku" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="SKU货号" align="center" prop="skuCode" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="产品名称" align="center" prop="productName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="SKU属性" align="center" prop="skuAttr" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="所属店铺" align="center" prop="shopName" width="120" />
      <el-table-column label="退货数量" align="center" prop="returnQuantity" width="100">
        <template slot-scope="scope">
          <span style="color: #E6A23C; font-weight: bold;">{{ scope.row.returnQuantity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="原出库数量" align="center" prop="originalOutboundQuantity" width="110" />
      <el-table-column label="退货日期" align="center" prop="returnDate" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['stock:return:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['stock:return:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改退货入库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="选择出库记录" prop="sourceOutboundId">
              <el-select 
                v-model="form.sourceOutboundId" 
                placeholder="请输入SKU或产品名称搜索" 
                filterable 
                remote
                :remote-method="remoteSearchOutbound"
                :loading="outboundLoading"
                style="width: 100%"
                :disabled="form.returnId != null"
                @change="handleOutboundChange"
                @visible-change="handleOutboundVisibleChange"
                ref="outboundSelect"
                popper-class="outbound-select-dropdown">
                <el-option
                  v-for="item in outboundOptions"
                  :key="item.outboundId"
                  :label="item.stockOrderNo + ' - ' + item.sku + ' - ' + item.productName + ' (可退' + item.availableReturnQuantity + '个)'"
                  :value="item.outboundId"
                  style="height: auto; line-height: normal; padding: 10px 20px;"
                >
                  <div style="line-height: 1.5;">
                    <div style="margin-bottom: 4px;">
                      <span style="font-weight: 500; color: #303133;">{{ item.stockOrderNo }}</span>
                      <span style="color: #909399; font-size: 12px; margin-left: 8px;">
                        出库{{ item.outboundQuantity }}个 | 已退{{ item.returnedQuantity }}个 | <span style="color: #67C23A; font-weight: 500;">可退{{ item.availableReturnQuantity }}个</span>
                      </span>
                    </div>
                    <div style="font-size: 13px; color: #606266;">
                      {{ item.sku }} - {{ item.productName }}
                    </div>
                  </div>
                </el-option>
                <el-option v-if="outboundHasMore && !outboundLoading" :value="null" disabled style="text-align: center;">
                  <span @click.stop="loadMoreOutbound" style="color: #409EFF; cursor: pointer;">加载更多...</span>
                </el-option>
                <el-option v-if="outboundLoading && outboundOptions.length > 0" :value="null" disabled style="text-align: center;">
                  <i class="el-icon-loading"></i> 加载中...
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU编码" prop="sku">
              <el-input v-model="form.sku" placeholder="选择出库记录后自动填充" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="选择出库记录后自动填充" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="退货数量" prop="returnQuantity">
              <el-input-number 
                v-model="form.returnQuantity" 
                :min="1" 
                :max="form.maxReturnQuantity || 999999" 
                placeholder="请输入退货数量" 
                style="width: 100%" />
              <span v-if="form.maxReturnQuantity" style="color: #909399; font-size: 12px; margin-left: 10px;">
                （可退数量：{{ form.maxReturnQuantity }}，出库{{ form.outboundQuantity }}个，已退{{ form.returnedQuantity || 0 }}个）
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="退货日期" prop="returnDate">
              <el-date-picker
                v-model="form.returnDate"
                type="datetime"
                placeholder="选择退货日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStockReturn, getStockReturn, delStockReturn, addStockReturn, updateStockReturn } from "@/api/business/stock"
import { listStockOutbound } from "@/api/business/stock"
import { getShopList } from "@/api/system/user"

export default {
  name: "StockReturn",
  computed: {
    outboundHasMore() {
      return this.outboundOptions.length < this.outboundTotal
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 退货入库表格数据
      returnList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 店铺选项
      shopOptions: [],
      // 出库记录选项
      outboundOptions: [],
      // 出库记录加载状态
      outboundLoading: false,
      // 出库记录分页参数
      outboundPageNum: 1,
      outboundPageSize: 20,
      outboundTotal: 0,
      outboundSearchKey: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sku: null,
        productName: null,
        shopId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sourceOutboundId: [
          { required: true, message: "请选择出库记录", trigger: "change" }
        ],
        returnQuantity: [
          { required: true, message: "退货数量不能为空", trigger: "blur" }
        ],
        returnDate: [
          { required: true, message: "退货日期不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getShopOptions()
    // 出库记录改为懒加载，打开下拉框时才加载
  },
  methods: {
    /** 查询退货入库列表 */
    getList() {
      this.loading = true
      listStockReturn(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.returnList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取店铺选项 */
    getShopOptions() {
      getShopList().then(response => {
        this.shopOptions = response.data
      })
    },
    /** 获取出库记录选项（支持分页加载） */
    getOutboundOptions(searchKey = '', isLoadMore = false) {
      this.outboundLoading = true
      
      // 如果不是加载更多，重置页码
      if (!isLoadMore) {
        this.outboundPageNum = 1
        this.outboundSearchKey = searchKey
      }
      
      const params = { 
        pageNum: this.outboundPageNum, 
        pageSize: this.outboundPageSize
      }
      
      // 如果有搜索关键字，添加搜索条件
      const key = isLoadMore ? this.outboundSearchKey : searchKey
      if (key) {
        // 判断是否为数字（可能是SKU或运单号）
        if (/^\d+$/.test(key)) {
          params.sku = key
        } else {
          // 同时搜索产品名称和运单号
          params.productName = key
          params.stockOrderNo = key
        }
      }
      
      listStockOutbound(params).then(response => {
        // 过滤掉可退货数量为0的记录
        const filteredRows = response.rows.filter(item => item.availableReturnQuantity > 0)
        
        // 如果是加载更多，追加数据；否则替换数据
        if (isLoadMore) {
          this.outboundOptions = [...this.outboundOptions, ...filteredRows]
        } else {
          this.outboundOptions = filteredRows
        }
        
        this.outboundTotal = response.total
        this.outboundLoading = false
      }).catch(() => {
        this.outboundLoading = false
      })
    },
    /** 远程搜索出库记录 */
    remoteSearchOutbound(query) {
      this.getOutboundOptions(query, false)
    },
    /** 加载更多出库记录 */
    loadMoreOutbound() {
      if (this.outboundLoading || !this.outboundHasMore) {
        return
      }
      this.outboundPageNum++
      this.getOutboundOptions(this.outboundSearchKey, true)
    },
    /** 下拉框显示/隐藏时的处理 */
    handleOutboundVisibleChange(visible) {
      if (visible) {
        if (this.outboundOptions.length === 0) {
          this.getOutboundOptions()
        }
        // 延迟重置滚动位置到顶部
        this.$nextTick(() => {
          const selectDropdown = document.querySelector('.outbound-select-dropdown .el-select-dropdown__wrap')
          if (selectDropdown) {
            selectDropdown.scrollTop = 0
          }
        })
      }
    },
    /** 出库记录改变时自动填充 */
    handleOutboundChange(outboundId) {
      const outbound = this.outboundOptions.find(o => o.outboundId === outboundId)
      if (outbound) {
        this.form.sku = outbound.sku
        this.form.productName = outbound.productName
        this.form.shopId = outbound.shopId
        // 使用可退货数量作为最大值
        this.form.maxReturnQuantity = outbound.availableReturnQuantity
        this.form.outboundQuantity = outbound.outboundQuantity
        this.form.returnedQuantity = outbound.returnedQuantity
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        returnId: null,
        sourceOutboundId: null,
        sku: null,
        productName: null,
        shopId: null,
        returnQuantity: null,
        returnDate: null,
        remark: null,
        maxReturnQuantity: null,
        outboundQuantity: null,
        returnedQuantity: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.returnId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 重新获取最新的出库记录列表
      this.getOutboundOptions()
      this.open = true
      this.title = "添加退货入库"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const returnId = row.returnId || this.ids
      getStockReturn(returnId).then(response => {
        this.form = response.data
        // 修改时，可退货数量 = 原出库数量 - 已退货数量 + 当前这条退货记录的数量（因为修改时可以恢复）
        const outbound = this.outboundOptions.find(o => o.outboundId === response.data.sourceOutboundId)
        if (outbound) {
          // 当前可退 + 本次退货数量（修改时可以改回）
          this.form.maxReturnQuantity = outbound.availableReturnQuantity + response.data.returnQuantity
          this.form.outboundQuantity = outbound.outboundQuantity
          this.form.returnedQuantity = outbound.returnedQuantity
        } else {
          // 如果找不到出库记录，说明可能已经被退完了，只能用原出库数量
          this.form.maxReturnQuantity = response.data.originalOutboundQuantity
          this.form.outboundQuantity = response.data.originalOutboundQuantity
          this.form.returnedQuantity = 0
        }
        this.open = true
        this.title = "修改退货入库"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.returnId != null) {
            updateStockReturn(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addStockReturn(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const returnIds = row.returnId || this.ids
      this.$modal.confirm('删除退货记录后将影响库存计算，是否确认删除？').then(function() {
        return delStockReturn(returnIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/stock/return/export', {
        ...this.queryParams
      }, `stock_return_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

